package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.PhoneVisit;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.PhoneVisitService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "phonevisit")
public class PhoneVisitController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private PhoneVisitService phoneVisitService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @RequestMapping(value = "listData", method = RequestMethod.GET)
    @ResponseBody
    public Page<PhoneVisit> listData(
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "hfName") String hfName,
        @RequestParam(required = false, value = "khName") String khName) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("phonevisit")) {
            Date start = null;
            Date end = null;
            if (StringUtils.isNotBlank(startTime)) {
                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (StringUtils.isNotBlank(endTime)) {
                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            Page<PhoneVisit> page = phoneVisitService.queryAllByParams(hfName, khName, start, end);

            return page;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("phonevisit")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("phonevisit/list");
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "memberRecord/{id}", method = RequestMethod.GET)
    public ModelAndView memberRecord(@PathVariable("id") Long id,
        @RequestParam(required = false, value = "param") String param) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("phonevisit")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("member/phonevisitlist");

            mv.addObject("page", phoneVisitService.queryByMember(id, param));
            mv.addObject("param", param);
            mv.addObject("memberId", id);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "loadMore", method = RequestMethod.POST)
    public @ResponseBody
    Page<PhoneVisit> loadMore(Integer page, Long memberId) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("phonevisit")) {

            return phoneVisitService.pageByMember(memberId, page, 5);
        }

        return null;

    }

    @RequestMapping(value = "add/{id}", method = RequestMethod.GET)
    public ModelAndView add(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("phonevisit")) {
            ModelAndView mv = new ModelAndView();

            Order order = orderService.findOne(id);

            mv.addObject("order", order);

            mv.addObject("phoneVisits", phoneVisitService.pageByMember(order.getClientId(), 0, 5));

            mv.setViewName("phonevisit/add");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "memberadd/{id}", method = RequestMethod.GET)
    public ModelAndView memberadd(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("phonevisit")) {
            ModelAndView mv = new ModelAndView();

            Passenger passenger = memberService.findOnePassenger(id);

            mv.addObject("passenger", passenger);

            mv.addObject("phoneVisits", phoneVisitService.pageByMember(passenger.getId(), 0, 5));

            mv.setViewName("phonevisit/memberadd");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Result<PhoneVisit> create(PhoneVisit phoneVisit) {

        Result<PhoneVisit> result = new Result<PhoneVisit>();

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("phonevisit")) {

            Order order = orderService.findOne(phoneVisit.getOrderId());
            phoneVisit.setAccountId(principal.getId());
            phoneVisit.setAccountName(principal.getUsername());
            phoneVisit.setMemberId(order.getClientId());
            phoneVisit.setOrderNumber(order.getOrderNumber());
            phoneVisit.setPhone(order.getClientPhone());
            phoneVisit.setCompanyId(order.getCompanyId());
            if (StringUtils.isBlank(phoneVisit.getOtherSatisfyInput())) {
                phoneVisit.setOtherSatisfy(null);
            }

            phoneVisitService.save(phoneVisit, order);

            String detail =
                "【%s】回访订单【" + order.getOrderNumber() + "】，客户：" + order.getClientName() + "(" + order
                    .getClientPhone() + ")";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);
            return result;
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "membercreate", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Result<PhoneVisit> membercreate(PhoneVisit phoneVisit) {

        Result<PhoneVisit> result = new Result<PhoneVisit>();

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("phonevisit")) {

            Passenger passenger = memberService.findOnePassenger(phoneVisit.getMemberId());

            phoneVisit.setAccountId(principal.getId());
            phoneVisit.setAccountName(principal.getUsername());
            phoneVisit.setPhone(passenger.getPhone());
            phoneVisit.setCompanyId(passenger.getCompanyId());

            if (StringUtils.isBlank(phoneVisit.getOtherSatisfyInput())) {
                phoneVisit.setOtherSatisfy(null);
            }

            phoneVisitService.save(phoneVisit);

            String detail = "【%s】回访客户【" + passenger.getName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);
            return result;
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }

    }


    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}

